const {shell} = require('electron');
const io = require('./io');
const Page = require('./pagination')
const WaveSurfer = require('../assets/wavesurfer');
require('../assets/common')

$('body').on('click','.open_file',function(){
    shell.openItem(__dirname + '/../audioDown')
})


let sm = require('./soundmgr');

let CurrentAudio;
/**
 * 浮点秒转换为mm:ss.hs形式的字符串
 * @param s 浮点秒
 */
function second_to_hs(s) {
    let m = Math.floor(s / 60);//分钟
    let second = s % 60;    //秒
    let sec = Math.floor(second);
    let hs = second - sec;
    m += '';
    sec += '';
    m = (m.length == 1) ? '0' + m : m;
    sec = (sec.length == 1) ? '0' + sec : sec;
    return m + ':' + sec + '.' + Math.floor(hs * 1000);
};

function GetElementById(id) {
    return $("#" + id);
}

function audio2suffix(isMusic) {
    return isMusic ? 'music' : 'sound';
}

function audio2tips(isMusic) {
    return isMusic ? '音乐' : '音效';
}

function UpdateMainTagsShown(TagTree, MainTagChange, ChildTagChange, Search, isMusic) {
    let suffix = audio2suffix(isMusic);
    let maintaglist = "MainTagList-{0}".format(suffix);
    if (TagTree == null) {
        document.getElementById(maintaglist).innerHTML = '';
        return;
    }
    let itemTemplate = "<span><button id='{1}-maintag-{0}' class='btn btn-default btn-sm {1}-tag-btn' style='margin:3px 10px;'>{0}</button></span>";
    let htmls = '';
    let first = null;
    let arr = new Array();
    for (let i in TagTree) {
        arr.push(i);
    }
    if (arr.length == 0) {
        document.getElementById(maintaglist).innerHTML = '';
        return;
    }
    arr.sort();
    for (let i of arr) {
        htmls += itemTemplate.format(i, suffix);
        if (first == null) {
            first = i;
        }
    }
    document.getElementById(maintaglist).innerHTML = htmls;

    let tagbutton = "button.{0}-tag-btn".format(suffix);
    $(tagbutton).bind("click", function () {
        MainTagChange($(this));

        UpdateChildTagsShown(TagTree, ChildTagChange, $(this).text(), Search, isMusic, suffix);
    });
    UpdateChildTagsShown(TagTree, ChildTagChange, first, Search, isMusic, suffix);
    let firstmaintagbutton = "#{0}-maintag-{1}".format(suffix, first);
    MainTagChange($(firstmaintagbutton));

    let AddTagAll = "AddTagAll-{0}".format(suffix);
    let addtagalll = 'addtagall-{0}'.format(suffix);
    document.getElementById(AddTagAll).innerHTML = FormatTagTreeHtml(TagTree, addtagalll, 'icon-plus');
    let RemoveTagAll = "RemoveTagAll-{0}".format(suffix);
    let removetagalll = 'removetagall-{0}'.format(suffix);
    document.getElementById(RemoveTagAll).innerHTML = FormatTagTreeHtml(TagTree, removetagalll, 'icon-minus');

    $("." + addtagalll).on("click", function () {
        let ids = GetCheckedIds();
        if (ids.length > 0) {
            let param = {
                isMusic: false,
                ids: ids,
                main: $(this).attr('maintag'),
                child: $(this).attr('childtag'),
                grandson: $(this).attr('childtag')
            };
            io.websocketemit('fileaddtag', param);
        }
    });

    $("." + removetagalll).on("click", function () {
        let ids = GetCheckedIds();
        if (ids.length > 0) {
            let param = {
                isMusic: false,
                ids: ids,
                main: $(this).attr('maintag'),
                child: $(this).attr('childtag'),
                grandson: $(this).attr('childtag')
            };
            io.websocketemit('fileremovetag', param);
        }
    });
}

function UpdateChildTagsShown(TagTree, ChildTagChange, maintag, Search, isMusic, suffix) {
    let htmls = "";
    let itemTemplate = "<span><button id='{1}-childtag-{0}' class='btn btn-default btn-sm {1}-childtag-btn' style='margin: 3px 10px;'>{0}</button></span>";
    let childtags = TagTree[maintag];
    if (childtags == null) {
        return;
    }
    let first = null;
    let arr = new Array();
    for (let i in childtags) {
        arr.push(i);
    }
    arr.sort();
    for (let i of arr) {
        htmls += itemTemplate.format(i, suffix);
        if (first == null) {
            first = i;
        }
    }
    let ChildTagList = "ChildTagList-{0}".format(suffix);
    document.getElementById(ChildTagList).innerHTML = htmls;
    let ChildTagPanel = "#ChildTagPanel-{0}".format(suffix);
    $(ChildTagPanel).css("display", "block");
    let childtagbtn = 'button.{0}-childtag-btn'.format(suffix);
    $(childtagbtn).bind("click", function () {
        ChildTagChange($(this));
        let inputsearch = '#inputSearch-{0}'.format(suffix);
        let searchsuffix = maintag + '.' + $(this).text();
        //let searchsuffix = $(this).text();
        console.log(searchsuffix);
        $(inputsearch).val(searchsuffix);
        Search(false, isMusic);
        UpdateGrandsonTagsShown(TagTree, maintag, $(this).text(), Search, isMusic, suffix);
    });
    UpdateGrandsonTagsShown(TagTree, maintag, first, Search, isMusic, suffix);
    let firstchildtagbutton = "#{0}-childtag-{1}".format(suffix, first);
    ChildTagChange($(firstchildtagbutton));
}

function UpdateGrandsonTagsShown(TagTree, maintag, childtag, Search, isMusic, suffix) {
    let htmls = "";
    let itemTemplate = "<span><button grandsontag='{0}' class='btn btn-default btn-sm {1}-grandsontag-btn' style='margin: 3px 10px;'>{0}</button></span>";
    let grandsontags = TagTree[maintag][childtag];
    let arr = new Array();
    for (let i of grandsontags) {
        arr.push(i);
    }
    arr.sort();
    for (let i of arr) {
        htmls += itemTemplate.format(i, suffix);
    }
    let GrandsonTagList = 'GrandsonTagList-{0}'.format(suffix);
    document.getElementById(GrandsonTagList).innerHTML = htmls; 
    let GrandsonTagPanel = '#GrandsonTagPanel-{0}'.format(suffix);
    $(GrandsonTagPanel).css("display", "block");
    let grandsontagbtn = 'button.{0}-grandsontag-btn'.format(suffix);
    $(grandsontagbtn).bind("click", function () {
        let inputsearch = '#inputSearch-{0}'.format(suffix);
        let searchsuffix = maintag + '.' + childtag + '.' + $(this).text();
        //let searchsuffix = $(this).attr('grandsontag');
        $(inputsearch).val(searchsuffix);
        Search(false, isMusic);
    });
}

function UpdateResoucesShown(Resources, pageIndex, TagTree, totalCount, pageCount, OnPageChange, isMusic,namespace) {
    let suffix = audio2suffix(isMusic);
    let resourceList = 'resourceList-{0}'.format(suffix);
    if (Resources == null) {
        document.getElementById(resourceList).innerHTML = '';
        return;
    }
    let itemTemplate = `
    <div class='audio-resource-item there-${namespace}'>
        <div class="checkbox" style="line-height: 27px;margin: 5px 20px;">
            <label>
            <input id='{0}' type='checkbox' class='zoom150 pkg-item-chk audio-checkbox {6}-check'/> 
            <span class='title-name' title='{1}' style='margin-right:5px;'>{1}</span>
            
            </label>
            <span suffix='{0}' class='glyphicon glyphicon-download btn-download-{6}'></span>
            <span suffix='{0}' name='{1}' class='{6}-delete-btn glyphicon glyphicon-trash' style='float:right;cursor: pointer;top: 10px;'></span>
        </div>

            <div style='overflow:hidden;margin: 0 0 15px 25px;'>
                <div id='waveform-{5}-${namespace}' style='width:447px;float:left;'></div>
                <div style='width:50px;float:left;'><input id='volume.{5}' suffix='{5}' type='range' class='input-range' value='1' max='2' mmin='0' step='0.2' style='transform:rotate(-90deg);margin: 45px 0 0 0;width:100px;'/></div>
            </div>
            <div style="float: left; width: 100px;margin: 0 0 0 15px;">
                <button class="btn btn-success btn-block playPause-${namespace}" suffix='{5}'>
                    <span suffix='{5}' class="btn-play-{6}">
                        <i class="glyphicon glyphicon-play"></i>
                        Play
                    </span>
                    <span suffix='{5}' style="display: none" class="btn-Pause-{6}">
                        <i class="glyphicon glyphicon-pause"></i>
                        Pause
                    </span>
                </button>
            </div>
            <div class='audio-resource-tags'>
                {3}
            </div>
 
    </div>`;

    let htmls = "";
    let tmpremovetag = "<button suffix='{0}' tag='{1}' class='btn btn-default btn-sm {2}-removetag-btn'><i class='icon-remove'></i>{1}</button> ";
    let tmpnewtag = "{0}</span>";
    for (let i = 0; i < Resources.length; i++) {
        let item = Resources[i];
        let tagspan = "<span>";
        if (item.tags != undefined) {
            for (let t = 0; t < item.tags.length; t++) {
                tagspan += tmpremovetag.format(item.id, item.tags[t], suffix);
            }
        }
        tagspan += tmpnewtag.format(FormatAddTagToFileButton(TagTree, item.id));
        htmls += itemTemplate.format(item.id, item.name, item.suffix, tagspan, io.geturl(), i, suffix);
    }
    document.getElementById(resourceList).innerHTML = htmls;
    window['Player_'+namespace] = new Array(Resources.length);
    for (let i = 0; i < Resources.length; i++) {
        window['Player_'+namespace][i] = WaveSurfer.create({
            container: '#waveform-' + i + '-' +namespace,
            waveColor: 'gray',
            progressColor: 'violet',
            height: 100,
        });
        let url = '{0}{1}{2}'.format(io.geturl(), Resources[i].id, Resources[i].suffix);
        $(window['Player_'+namespace][i].params.container).parents('.audio-resource-item').find('.' + namespace + '-check').attr('url',url)   

        window['Player_'+namespace][i].load(url);
        window['Player_'+namespace][i].on('play', function () {
            $(window['Player_'+namespace][i].params.container).parents('.audio-resource-item').find('.btn-play-'+namespace).hide();
            $(window['Player_'+namespace][i].params.container).parents('.audio-resource-item').find('.btn-Pause-' +namespace).show();
            // $("span.btn-play-{0}".format(suffix)).hide();
            // $("span.btn-Pause-{0}".format(suffix)).show();
        });
        window['Player_'+namespace][i].on('pause', function () {
            $(window['Player_'+namespace][i].params.container).parents('.audio-resource-item').find('.btn-play-' +namespace).show();
            $(window['Player_'+namespace][i].params.container).parents('.audio-resource-item').find('.btn-Pause-' +namespace).hide();
        });
    }


    $("span.{0}-delete-btn".format(suffix)).bind("click", function () {
        OnClickDeleteFile($(this).attr('suffix'), $(this).attr('name'), isMusic);
    });
    $("button.{0}-removetag-btn".format(suffix)).bind("click", function () {
        let param = {
            isMusic: isMusic,
            tag: $(this).attr('tag'),
            ids: [$(this).attr('suffix')]
        };
        io.websocketemit('fileremovetag', param);
    });
    $("button.{0}-newtag-btn".format(suffix)).bind("click", function () {
        BtnFileAddTag($(this).attr('suffix'));
    });
    $(".btn-download-{0}".format(suffix)).bind("click", function () {
        let param = {
            isMusic: isMusic,
            id: $(this).attr('suffix')
        };
        io.websocketemit('download', param);
    });
    $(".playPause-" + namespace).on('click', function () {
        var i = $(this).attr('suffix')
        window['Player_'+namespace][i].playPause();
    });


    // $(".btn-play-{0}".format(suffix)).bind("click", function () {       
    //     let suffix = $(this).attr('suffix');
    //     if (CurrentAudio) {
    //         CurrentAudio.stop();
    //     }
    //     CurrentAudio = Player[suffix];
    //     CurrentAudio.play();
    // });
    $(".input-range".format(suffix)).bind("mousemove", function () {           
        let suffix = $(this).attr('suffix');   
        CurrentAudio = window['Player_'+namespace][suffix];
        if(CurrentAudio == null)
            return;
        //设置音量
        var volumevalue = document.getElementById("volume." + suffix).value;
        CurrentAudio.setVolume(volumevalue);
    });
    if (pageIndex == 0) {
        SetupPagination(totalCount, pageCount, OnPageChange, isMusic);
    }
}

function SetupPagination(totalCount, count, OnPageChange, isMusic) {
    let suffix = audio2suffix(isMusic);
    new Page.Page({
        id: 'pagination-{0}'.format(suffix),
        pageTotal: Math.ceil(totalCount / count), //必填,总页数
        pageAmount: count,  //每页多少条
        dataTotal: totalCount, //总共多少条数据
        curPage: 1, //初始页码,不填默认为1
        pageSize: 15, //分页个数,不填默认为5
        showPageTotalFlag: true, //是否显示数据统计,不填默认不显示
        showSkipInputFlag: true, //是否支持跳转,不填默认不显示
        getPage: function (page) {
            OnPageChange(page, count);
        },
        onchange: function (count) {
            SetupPagination(totalCount, count, isMusic);
            OnPageChange(0, count);
        }
    });
}

function OnClickDeleteFile(id, name, isMusic) {
    let tips = audio2tips(isMusic);
    const options = {
        type: 'info',
        title: 'Delete Audio File',
        message: '确认删除{0}文件:\n{1}?'.format(tips, name),
        buttons: ['删除', '取消']
    }

    dialog.showMessageBox(options, (index) => {
        if (index === 0) {
            let param = {
                isMusic: isMusic,
                ids: [id]
            };
            io.websocketemit('removefile', param);
        }
    })
}

function OnClickDeleteFileAll(isMusic) {
    let tips = audio2tips(isMusic);
    let ids = GetCheckedIds();
    if (ids.length > 0) {
        const options = {
            type: 'info',
            title: 'Delete Audio File',
            message: '确认删除这{0}个{1}文件?'.format(ids.length, tips),
            buttons: ['删除', '取消']
        }

        dialog.showMessageBox(options, (index) => {
            if (index === 0) {
                let param = {
                    isMusic: isMusic,
                    ids: ids
                };
                io.websocketemit('removefile', param);
            }
        })
    }
}

function GetCheckedIds(isMusic) {
    let ids = [];
    let suffix = audio2suffix(isMusic);
    $(".{0}-check".format(suffix)).each(function () {
        if ($(this).prop("checked")) {
            ids.push($(this).attr("id"));
        }
    });

    if (ids.length == 0) {
        alert("请先勾选音效，再执行操作！");
    }
    return ids;
}

function OnClickImport(isMusic) {
    let param = {
        isMusic: isMusic,
        index: 0,
        count: 0
    };
    io.websocketemit('import', param);
}

function OnClickClean(isMusic) {
    let param = {
        isMusic: isMusic,
    };
    io.websocketemit('clean', param);
}

/**
 * 通用的打开下载对话框方法，没有测试过具体兼容性
 * @param url 下载地址，也可以是一个blob对象，必选
 * @param saveName 保存文件名，可选
 */
function DownloadAudio(url, name) {
    if (typeof url == 'object' && url instanceof Blob) {
        url = URL.createObjectURL(url); // 创建blob地址
    }
    // ipcRenderer.send('download',url)
    let aLink = document.createElement('a');
    aLink.href = url;
    aLink.download = name; // HTML5新增的属性，指定保存文件名，可以不要后缀，注意，file:///模式下不会生效
    let event;
    if (window.MouseEvent) event = new MouseEvent('click');
    else {
        event = document.createEvent('MouseEvents');
        event.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
    }
    aLink.dispatchEvent(event);
    alert("文件将下载到本地！")
}

function DownloadAudioData(data) {
    DownloadAudio(new Blob([data.wav], { type: 'audio/wav' }), data.name);
}

function GetFile(files, id) {
    if (files == undefined) {
        return null;
    }
    for (let i = 0; i < files.length; i++) {
        let item = files[i];
        if (item.id == id) {
            return item;
        }
    }
    return null;
}

function FormatTagTreeHtml(TagTree, classKey, icon) {
    let htmls = '';
    for (let i in TagTree) {
        htmls += "<li class='dropdown-submenu'><a tabindex='-1' href='#'>{0}</a><ul class='dropdown-menu'>".format(i);
        let childtags = TagTree[i];
        for (let j in childtags) {
            htmls += "<li class='dropdown-submenu'><a href='#'>{0}</a><ul class='dropdown-menu'><li>".format(j);
            let grandsontags = TagTree[i][j];
            for (let k of grandsontags) {
                htmls += "<li class='{0}' maintag='{1}' childtag='{2}' grandsontag='{3}'><a href='#'><i class='{4}'></i>{3}</a></li>".format(classKey, i, j, k, icon);
            }
            htmls += "</ul></li>";
        }
        htmls += "</ul></li>";
    }
    return htmls;
}

function FormatAddTagToFileButton(TagTree, fileid) {
    let htmls = "<div class='btn-group dropdown'>\
    <button type='button' class='btn btn-default btn-sm'><i class='icon-plus'></i>标签</button>\
    <button type='button' class='btn btn-default btn-sm dropdown-toggle' data-toggle='dropdown' aria-haspopup='true' aria-expanded='false'>\
      <span class='caret'></span>\
      <span class='sr-only'>Toggle Dropdown</span>\
    </button>\
    <ul class='dropdown-menu'>";
    for (let i in TagTree) {
        htmls += "<li class='dropdown-submenu'><a tabindex='-1' href='#'>{0}</a><ul class='dropdown-menu'>".format(i);
        let childtags = TagTree[i];
        for (let j in childtags) {
            htmls += "<li class='dropdown-submenu'><a href='#'>{0}</a><ul class='dropdown-menu'><li>".format(j);
            let grandsontags = TagTree[i][j];
            for (let k of grandsontags) {
                htmls += "<li class='addchildtag' fileid='{0}' maintag='{1}' childtag='{2}' grandsontag='{3}'><a href='#'><i class='icon-plus'></i>{3}</a></li>".format(fileid, i, j, k);
            }
            htmls += "</ul></li>";
        }
        htmls += "</ul></li>";
    }
    htmls += "</ul></div>";
    return htmls;
}

function RegistClickEvents(isMusic, Download, Search, NewTag) {
    let suffix = audio2suffix(isMusic);
    let btnImport = 'btnImport-{0}'.format(suffix);
    GetElementById(btnImport).click(() => {
        OnClickImport(isMusic);
    })

    let btnClean = 'btnClean-{0}'.format(suffix);
    GetElementById(btnClean).click(() => {
        OnClickClean(isMusic);
    })

    let inputSearch = 'inputSearch-{0}'.format(suffix);
    GetElementById(inputSearch).bind('input propertychange', () => {
        Search(false, isMusic);
    })

    let SelectAll = 'SelectAll-{0}'.format(suffix);
    GetElementById(SelectAll).click(() => {
        let sCheck = GetElementById('sCheck-{0}'.format(suffix));
        let iCheck = GetElementById('iCheck-{0}'.format(suffix));
        if (iCheck.hasClass('icon-ok')) {//全选
            sCheck.text("取消全选");
            iCheck.removeClass("icon-ok");
            iCheck.addClass("icon-remove");
            $("input.{0}-check".format(suffix)).attr("checked", 'true');
        }
        else {//取消全选
            sCheck.text("全选");
            iCheck.removeClass("icon-remove");
            iCheck.addClass("icon-ok");
            $("input.{0}-check".format(suffix)).removeAttr("checked");
        }
    })

    let DownloadAll = 'DownloadAll-{0}'.format(suffix);
    GetElementById(DownloadAll).click(() => {
        let ids = GetCheckedIds(isMusic);
        if (ids.length > 0) {
            Download(ids);
        }
    })

    let DeleteAll = 'DeleteAll-{0}'.format(suffix);
    GetElementById(DeleteAll).click(() => {
        OnClickDeleteFileAll(isMusic);
    })

    let newtag = 'newtag-{0}'.format(suffix);
    GetElementById(newtag).click(() => {
        let inputTip = $("#inputTip-{0}".format(suffix));

        let tag = inputTip.val();
        if (tag == "") {
            alert("请输入标签！");
            return;
        }
        NewTag(tag, isMusic);
        inputTip.val("");
    })

    RequestTotal(isMusic);
    RequestTagList(isMusic);
    Search(false, isMusic);
}

function RequestTotal(isMusic) {
    let param = { isMusic: isMusic };
    io.websocketemit('total', param);
}

function RequestTagList(isMusic) {
    let param = { isMusic: isMusic };
    io.websocketemit('gettaglist', param);
}

function RequestNewTag(main,child,grandson,isMusic){
    let param = {
        isMusic: isMusic,
        maintag: main,
        child: child,
        grandson: grandson
    };
    io.websocketemit('newtag', param);
}

function RequestSearch(page, count, refresh, isMusic) {
    let suffix = audio2suffix(isMusic);
    let inputsearch = $('#inputSearch-{0}'.format(suffix));
    if (page == null){
        page = 0;
    }
    if (count == null){
        count = 20;
    }
    let param = {
        key: inputsearch.val(),
        order: 'name',
        index: page,
        count: count,
        refresh: refresh,
        isMusic: isMusic
    }
    // console.log(param)
    io.websocketemit('search', param);
}

function OnProgress(val, Search, isMusic) {
    let suffix = audio2suffix(isMusic);
    if (val == 100) {
        GetElementById('btnImport-{0}'.format(suffix)).text("导入");
        RequestTotal(isMusic);
        RequestTagList(isMusic);
        RequestSearch(sm.CurrentSoundPage,sm.SoundPageCount,false, isMusic);
    } else {
        GetElementById('btnImport-{0}'.format(suffix)).text(val + "%");
    }
}

function RefreshSearch(success, msg, isMusic, Search) {
    if (success) {
        Search(true, isMusic);
    }
    else {
        alert(msg);
    }
}

function RegistWS(isMusic) {
    let suffix = audio2suffix(isMusic);
    io.onwebsocket('download-{0}'.format(suffix), (data) => {
        DownloadAudioData(data);
    });

    io.onwebsocket('addtag-{0}'.format(suffix), (success) => {
        RefreshSearch(success, 'file add tag fail.', isMusic, RequestSoundSearch);
    });

    io.onwebsocket('removetag-{0}'.format(suffix), (success) => {
        RefreshSearch(success, 'file remove tag fail.', isMusic, RequestSoundSearch);
    });

    io.onwebsocket('remove-{0}'.format(suffix), (success) => {
        RefreshSearch(success, 'delete file tag fail.', isMusic, RequestSoundSearch);
    });

    io.onwebsocket('totalcount-{0}'.format(suffix), (data) => {
        GetElementById('total-{0}'.format(suffix)).text(data.count);
    });

    io.onwebsocket('progress-{0}'.format(suffix), (data) => {
        OnProgress(data.value, null, isMusic);
    });

    io.onwebsocket('clean-{0}'.format(suffix), (data) => {
        GetElementById('btnClean-{0}'.format(suffix)).text("清理");
        RequestTotal(isMusic);
    });
}

module.exports = {
    second_to_hs,
    OnProgress,
    UpdateMainTagsShown,
    RequestSearch,
    RequestNewTag,
    UpdateResoucesShown,
    DownloadAudioData,
    RegistWS,
    RegistClickEvents,
    GetFile,
    RequestTotal,
    RefreshSearch,
    GetElementById,
}